﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Collections;
using Microsoft.Office.Server.UserProfiles;
using System.Collections.Generic;

namespace Trig_AMJ_HR_Forms.Layouts.Trig_AMJ_HR_Forms
{
    public partial class Clearance_Action_Form : LayoutsPageBase
    {

        //http://csharpdotnetfreak.blogspot.com/2009/07/display-total-in-gridview-footer.html

        decimal grdTotal = 0;
        public static string Accountablity;

        SPHelper obj = new SPHelper();
        Demand_Voucher_FormClass demandVoucherclass = new Demand_Voucher_FormClass(); // Helper class for this solution
        Trig_WF trigWFClass = new Trig_WF();

        #region "Properties"

        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

        public static string SiteURL;
        public static string ClearanceRequestNo;
        public static string SourceLstName;
        public static string MainLstName;
        public static string TaskLstName;
        public static string AccountablityLstName;
        public static string AttLibName;
        public static string CmntsLstName;
        public static string WorkflowConfigList;
        public static string lstGuid { get; set; }
        public string camlQry;
        public static string Mode;
        public static string TaskItemID;
        public static string submittedfor;
        string ErrorMsgs;
        public static int wfOrder = 0;
        public static string DocumentTypesList;
        public static string WFCurrentOrder = string.Empty;
        string WFTaskType = string.Empty;

        public static string LeaveRefID;
        public static string refID;

        public static int ClearanceItemID;

        List<Users> wfUsers = new List<Users>();

        public static List<string> lstUsers = new List<string>();

        public static SPUser reqUser;

        string[] buttonVisibilty = new string[5];

        private static SPListItemCollection oItemsColl = null;
        private static SPListItem oItems = null;

        public static string ClearanceType = null;

        public static bool CKClear = false;

        public static string DeptName;


        public static SPFieldUserValue pkrReqUser = null;

        #endregion

        /// <summary>
        /// Class used to bind Approval users to generic list.
        /// It will used to check assign approval user for accountants on by one
        /// </summary>
        public class Users
        {
            public string user { get; set; }
        }

        public Clearance_Action_Form()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Clearance Forms";
            TaskLstName = "Clearance Tasks";
            CmntsLstName = "Clearance Comments";
            SourceLstName = "Leave Request Forms";
            AttLibName = "Attachments";
            WorkflowConfigList = "Workflow Configuration List";
            DocumentTypesList = "DocumentTypes";
            AccountablityLstName = "User Clearance Accountablities";
        }

        /// <summary>
        /// Clearance Action form is submitted by directly or using Leave Request Dashboards
        /// Depends upon we get corresponding reference id or leave reference number.
        /// The Approval process starts from User department accountant, who check the accoutablity and submit the form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        protected void Page_Load(object sender, EventArgs e)
        {
            lblError.Text = "";
            try
            {
                
                lblErrors.Text = ""; lblErrors.Visible = false;

                if (!IsPostBack)
                {
                    ckSubmit.Value = "false";
                    Mode = Request.QueryString["Mode"];
                    refID = Request.QueryString["RefID"]; // From Dashboard.
                    LeaveRefID = Request.QueryString["LeaveRefID"]; // From Dashboard.
                    TaskItemID = Convert.ToString(Request.QueryString["TaskItemID"]);

                    ClearanceType = null;
                    dtReqDate.SelectedDate = DateTime.Today;
                    ImgUser.ImageUrl = demandVoucherclass.GetUserProfilePictureURL(CurrentUser);
                    LblCommentsUserName.Text = CurrentUser;

                    if (Mode == "Edit" || Mode == "View")
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            FormApprovalLoad();
                            pnlAccMain.Visible = true; // Accountant fill this controls
                            pnlAccountablity.Visible = true; // To view the previous accounts accountablities
                            if (gvAccountablity.Rows.Count == 4)
                                pnlAccountablity.Visible = false;
                            if (Mode == "View") InvisibleButtons();
                            pplReqUser.Enabled = false;
                        });
                    }
                    else if (Mode == "New")
                    {
                        pnlAccMain.Visible = false;    // Show only the accountant users
                        pnlAccountablity.Visible = false; // Show only the accountant users
                        ClearanceType = rdClearanceType.SelectedItem.Text;
                        if (refID != null || LeaveRefID != null)
                        {
                            FirstLoadofForm();
                        }

                    }
                    else
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Unable to open the form. Value is missing. Contact administrator";
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: HR Request form" + " :: " + "Parent" + " :: " + "Page_Load";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            // Get SubmittedFor user details 
            // function not fired while form gets submitted
            if (Mode == "New" && ckSubmit.Value == "false") GetUserInfo();


            AssignedNotMe();
            
        }


        /// <summary>
        /// To check whether the Form is in Document Types master list or not.
        /// Also get the document prefix and starting number of the form
        /// Otherwise the user gets Access Denied
        /// </summary>
        private void FirstLoadofForm()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string[] getDocRefNumber = demandVoucherclass.getRefNum(SiteURL, DocumentTypesList, MainLstName);
                    if (string.IsNullOrEmpty(getDocRefNumber[0]) && string.IsNullOrEmpty(getDocRefNumber[1]))
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Access Denied, DocPrefix or Starting Number column value in Document Types Master list is missing. Contact administrator.";
                    }

                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Clearance Action Form" + " :: " + "Parent" + " :: " + "FirstLoadofForm";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        protected void rdClearanceType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (rdClearanceType.SelectedIndex == 0)
                {// To show the SubmittedFor leave refernce number and leave request date.  
                    trLeaves.Visible = true;
                    trLeaves1.Visible = true;
                }
                else
                {
                    trLeaves.Visible = false;
                    trLeaves1.Visible = false;
                }

                ClearanceType = rdClearanceType.SelectedItem.Text;
                ClearControls();
                btnSubmit.Visible = true;
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Clearance Action Form" + " :: " + "Parent" + " :: " + "rdClearanceType_SelectedIndexChanged";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        private void ClearControls()
        {
            pplReqUser.Entities.Clear();
            txtReqEmpId.Text = ""; txtReqDesignation.Text = ""; txtReqDivision.Text = ""; dtEffectiveon.ClearSelection();
            txtLeaveRefNo.Text = ""; dtLeaveReqDate.ClearSelection();
        }

        protected void rdAccountablity_SelectedIndexChanged(object sender, EventArgs e)
        {

        }



        /// <summary>
        /// Get submittedFor details from Leave Request List when the clearance status is "No"
        /// This process to be access by New form entry or through Leave Request Dashboard 
        /// </summary>
        private void GetUserInfo()
        {
            try
            {

                ClearClearanceControls();

                if (LeaveRefID != null)
                {
                    GetLeaveUser(pplReqUser); // If SubmittedFor user has a leave, this function retrieve datas.also it get and set the user on the People Editor controls
                    rdClearanceType.Enabled = false;
                    //pplReqUser.Enabled = false;
                }

                else if (pplReqUser.ResolvedEntities.Count > 0)
                {
                    if (rdClearanceType.SelectedIndex == 0)
                    {
                        PickerEntity pe = (PickerEntity)pplReqUser.Entities[0];
                        string submittedFor = pe.DisplayText;

                        camlQry = "<Where><And><Eq><FieldRef Name=\"SubmittedFor\" /><Value Type=\"User\">" + submittedFor + "</Value></Eq><Eq>" +
                            "<FieldRef Name=\"ClearanceStatus\" /><Value Type=\"Text\">No</Value></Eq></And></Where>";
                        oItems = obj.GetSPListItem(SiteURL, SourceLstName, camlQry);
                        if (oItems != null)
                        {
                            SetClearanceControls(oItems); btnSubmit.Visible = true;
                        }
                        else
                        {
                            btnSubmit.Visible = false;
                            pplReqUser.Entities.Clear();
                            pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('No Leave records for selected user!');</script>"));
                            //lblErrors.Visible = true; lblErrors.Text = "";
                        }
                    }
                    else
                    {
                        GetEmpInfo();
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Clearance Action Form" + " :: " + "Parent" + " :: " + "GetUserInfo";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        /// <summary>
        /// Get Leave taken user from Leave Request Form, and assign values to corresponding controls in this form
        /// </summary>
        /// <param name="ppls"></param>
        private void GetLeaveUser(PeopleEditor ppls)
        {

            try
            {
                ArrayList _arrayList = new ArrayList();

                SPFieldUserValue fldUser = null;
                SPQuery qry = new SPQuery();
                camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + LeaveRefID + "</Value></Eq></Where>";
                qry.Query = camlQry;
                //qry.ViewFields = "<FieldRef Name='SubmittedFor' />";
                oItems = obj.GetSPListItem(SiteURL, SourceLstName, qry);
                if (oItems != null)
                {
                    fldUser = new SPFieldUserValue(SPContext.Current.Web, Convert.ToString(oItems["SubmittedFor"]));
                    PickerEntity _pickerEntity = new PickerEntity(); // PickerEntitiy use using Microsoft.SharePoint.WebControls
                    _pickerEntity.Key = fldUser.LookupValue;
                    _pickerEntity.IsResolved = true;
                    _arrayList.Add(_pickerEntity);
                    ppls.UpdateEntities(_arrayList);
                    SetClearanceControls(oItems);
                }
                else
                {

                }
            }

            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Clearance Action Form" + " :: " + "Parent" + " :: " + "GetLeaveUser";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        /// <summary>
        /// Get SubmittedFor user details from SharePoint User Profile
        /// </summary>
        private void GetEmpInfo()
        {
            string user = null;
            PickerEntity pe = (PickerEntity)pplReqUser.Entities[0];
            string submittedFor = pe.DisplayText;

            if (!string.IsNullOrEmpty(submittedFor))
            {
                GetCurrentUserDetails(submittedFor, txtReqEmpId, txtReqDivision, txtReqDepartment, txtReqDesignation);
            }
        }


        /// <summary>
        /// Get SubmittedFor user properties from User Profile
        /// </summary>
        /// <param name="AccountName"></param>
        /// <param name="id"></param>
        /// <param name="division"></param>
        /// <param name="designation"></param>
        public void GetCurrentUserDetails(string AccountName, TextBox id, TextBox division, TextBox department, TextBox designation)
        {
            try
            {
                id.Text = null; division.Text = null; designation.Text = null;
                UserProfile userProfile = obj.GetUserInfo(AccountName);
                obj.checkField(userProfile, id, "EmployeeID");
                obj.checkField(userProfile, division, "Division");
                obj.checkField(userProfile, department, "Department");
                obj.checkField(userProfile, designation, "Designation");

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "GetCurrentUserDetails";
                //GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        /// <summary>
        /// This function is fired while the Approval user Approved the form.
        /// If the Approval user department is Human Resource, that time the next Approval Task will be assigned to SubmittedFor user. 
        /// </summary>
        /// <returns></returns>
        private string GetEmpDept()
        {
            string user = null;
            user = SPContext.Current.Web.CurrentUser.LoginName;
            if (!string.IsNullOrEmpty(user))
            {
                UserProfile userProfile = obj.GetUserInfo(user);
                if (userProfile["Department"].Value != null)
                    DeptName = userProfile["Department"].Value.ToString();
            }
            return DeptName;
        }


        private void ClearClearanceControls()
        {
            txtReqEmpId.Text = ""; txtReqDesignation.Text = ""; txtReqDivision.Text = ""; dtEffectiveon.ClearSelection();
            txtLeaveRefNo.Text = ""; dtLeaveReqDate.ClearSelection(); dtLeaveStartDT.ClearSelection(); dtLeaveEndDT.ClearSelection();
        }

        private void SetClearanceControls(SPListItem oItems)
        {
            txtReqEmpId.Text = Convert.ToString(oItems["EmployeeID"]);
            txtReqDivision.Text = Convert.ToString(oItems["Division"]);
            txtReqDesignation.Text = Convert.ToString(oItems["Designation"]);
            txtReqDivision.Text = Convert.ToString(oItems["Division"]);
            txtLeaveRefNo.Text = Convert.ToString(oItems["Reference_x0020_Number"]);
            dtLeaveReqDate.SelectedDate = Convert.ToDateTime(oItems["RequestDate"]);
            dtLeaveStartDT.SelectedDate = Convert.ToDateTime(oItems["TravelDate"]);
            dtLeaveEndDT.SelectedDate = Convert.ToDateTime(oItems["ReturnDate"]);
        }

        /// <summary>
        /// Get Approver user from task list and check their properties from Workflow Configuration List
        /// Based upon the properties the buttons and radio button should be shown in the screen.
        /// Also bind Submitted details from Master List
        /// </summary>
        public void FormApprovalLoad()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (!string.IsNullOrEmpty(TaskItemID))
                    {
                        using (SPSite FrmSite = new SPSite(SiteURL))
                        {
                            using (SPWeb frmweb = FrmSite.OpenWeb())
                            {
                                SPQuery updatecamQ = new SPQuery();
                                updatecamQ.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + TaskItemID + "</Value></Eq></Where>";
                                if (frmweb.Lists.TryGetList(TaskLstName) != null)
                                {
                                    SPListItemCollection oitemcoll = frmweb.Lists.TryGetList(TaskLstName).GetItems(updatecamQ);
                                    if (oitemcoll.Count > 0)
                                    {
                                        SPListItem oitm = oitemcoll[0];
                                        WFCurrentOrder = Convert.ToString(oitm["WFCurrentOrder"]);
                                        hdnWF_Order.Value = WFCurrentOrder;
                                        WFTaskType = Convert.ToString(oitm["WFTaskType"]);
                                        if (WFTaskType == "Dynamic")
                                        {
                                            pnlForward.Visible = true;
                                        }
                                        RadioButtionListvisibility(frmweb, WFTaskType, false, "", Convert.ToInt32(WFCurrentOrder));
                                    }
                                }
                            }
                        }
                    }

                    ReLoadDetails();
                    GetTaskUsers(); // It used to check with generic list users. and assign task to remaining accountant.



                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "FormApprovalLoad";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        #region "Reload Forms"

        public void ReLoadDetails()
        {
            try
            {

                if (refID != null)
                    camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refID + "</Value></Eq></Where>";
                if (LeaveRefID != null)
                    camlQry = "<Where><Eq><FieldRef Name=\"LeaveReferenceNo\" /><Value Type=\"Text\">" + LeaveRefID + "</Value></Eq></Where>";

                SPListItem lstDatas = obj.GetSPListItem(SiteURL, MainLstName, camlQry);
                if (lstDatas != null)
                {

                    lblClrReqNo.Text = Convert.ToString(lstDatas["Reference Number"]);
                    dtReqDate.SelectedDate = Convert.ToDateTime(lstDatas["RequestDate"]);

                    //Label lblFormID = ClrComments.FindControl("lblFormID") as Label;
                    //lblFormID.Text = lstDatas.ParentList.ID.ToString();

                    lstGuid = lstDatas.ParentList.ID.ToString();

                    SetValuesToControls(lstDatas);

                    Label lblreferenceNumber = ClrComments.FindControl("lblReferenceNumber") as Label;
                    Label lblSiteUrl = ClrComments.FindControl("lblSiteUrl") as Label;
                    Label lblfrmListName = ClrComments.FindControl("lblfrmListName") as Label;
                    Label lbldocumentypesList = ClrComments.FindControl("lbldocumentTypes") as Label;
                    Label lblCommentsList = ClrComments.FindControl("lblCommentsList") as Label;
                    Label lblTaskList = ClrComments.FindControl("lblTaskList") as Label;

                    lblTaskList.Text = TaskLstName;
                    lblCommentsList.Text = CmntsLstName;
                    lblfrmListName.Text = MainLstName;
                    lbldocumentypesList.Text = DocumentTypesList;
                    lblreferenceNumber.Text = lblClrReqNo.Text;
                    lblSiteUrl.Text = SiteURL;
                    GetSetUserAccountablity();

                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Clearance Action Form" + " :: " + "Parent" + " :: " + "ReLoadDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        #endregion

        /// <summary>
        /// Get Approval Users from corresponding task list.
        /// It will be used to check with Division Accountant user, and the task will be assigned to remaining user of collection[0]
        /// </summary>
        private void GetTaskUsers()
        {
            try
            {
                lstUsers.Clear();
                SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            using (SPSite oSite = new SPSite(SiteURL))
                            {
                                using (SPWeb oWeb = oSite.OpenWeb())
                                {
                                    SPList oLstTask = oWeb.Lists.TryGetList(TaskLstName);
                                    if (oLstTask != null)
                                    {
                                        SPQuery qry = new SPQuery();

                                        camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refID + "</Value></Eq></Where>";
                                        qry.Query = camlQry;
                                        //qry.ViewFields = "FieldRef Name=\"AssignedTo\" />";
                                        oItemsColl = oLstTask.GetItems(qry);

                                        if (oItemsColl.Count > 0)
                                        {
                                            int wf = oItemsColl.Count;

                                            if (wf == 6)
                                            {
                                                btnSubmit.Text = "Submit";
                                            }


                                            foreach (SPListItem oItem in oItemsColl)
                                            {
                                                Users user = new Users();
                                                SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                                                user.user = fldUser.LookupValue;
                                                wfUsers.Add(user);
                                                // string.Concat(lstUsers, GetDivisionForUsers(fldUser.LookupValue));
                                            }
                                            foreach (var user in wfUsers)
                                            {
                                                lstUsers.Add(user.user);
                                            }
                                        }

                                    }
                                }
                            }

                        });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Clearance Action Form" + " :: " + "Parent" + " :: " + "GetTaskUsers";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");

            }

        }


        private string GetDivisionForUsers(string accManager)
        {
            string Division = null;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPQuery qry = new SPQuery();
                            camlQry = "<Where><Eq><FieldRef Name=\"Accountant\" /><Value Type=\"User\">" + accManager + "</Value></Eq></Where>";
                            qry.Query = camlQry;
                            qry.ViewFields = "<FieldRef Name=\"Title\" />";
                            oItems = obj.GetSPListItem(SiteURL, "Divisions", qry);
                            if (oItems != null)
                            {
                                Division = Convert.ToString(oItems["Title"]);
                            }
                        }
                    }

                });
            }
            catch (Exception ex)
            {

            }
            return Division;
        }

        private void SetValuesToControls(SPListItem lstDatas)
        {
            refID = Convert.ToString(lstDatas["Reference_x0020_Number"]);
            LeaveRefID = Convert.ToString(lstDatas["LeaveReferenceNo"]);

            ClearanceType = Convert.ToString(lstDatas["ClearanceType"]);
            rdClearanceType.Items.FindByText(ClearanceType).Selected = true;


            if (Convert.ToInt32(rdClearanceType.Items.FindByText(ClearanceType).Value) == 0)
            {
                trLeaves.Visible = true; trLeaves1.Visible = true;
                LeaveRefID = Convert.ToString(lstDatas["LeaveReferenceNo"]);
                txtLeaveRefNo.Text = LeaveRefID;
                dtLeaveReqDate.SelectedDate = Convert.ToDateTime(lstDatas["LeaveRequestDate"]);
                dtLeaveStartDT.SelectedDate = Convert.ToDateTime(lstDatas["TravelDate"]);
                dtLeaveEndDT.SelectedDate = Convert.ToDateTime(lstDatas["ReturnDate"]);
            }
            else
            {
                trLeaves.Visible = false; trLeaves1.Visible = false;
            }
            rdClearanceType.Enabled = false;

            SetPickerEntry(pplReqUser, Convert.ToString(lstDatas["SubmittedFor"]));
            txtReqEmpId.Text = Convert.ToString(lstDatas["EmployeeID"]);
            txtReqDesignation.Text = Convert.ToString(lstDatas["Designation"]);
            txtReqDivision.Text = Convert.ToString(lstDatas["Division"]);
            txtReqDepartment.Text = Convert.ToString(lstDatas["Department"]);
            dtEffectiveon.SelectedDate = Convert.ToDateTime(lstDatas["EffectineOn"]);
            dtEffectiveon.Enabled = false;

            submittedfor = Convert.ToString(lstDatas["SubmittedFor"]);
            SPFieldUserValue fldUser = new SPFieldUserValue(SPContext.Current.Web, submittedfor);
            submittedfor = fldUser.LookupValue;

            ClearanceItemID = Convert.ToInt32(lstDatas["ID"]);


            if (SPContext.Current.Web.CurrentUser.LoginName.ToLower().Contains(pplReqUser.CommaSeparatedAccounts.ToLower()))
            {
                btnApprove.Text = "Confirm"; btnReject.Visible = false;
                plnSettle.Visible = true;
            }
            else
            {
                plnSettle.Visible = false;
            }
            if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["OSSettlement"])))
            {
                pnlOSView.Visible = true;
                txtSettlement.Text = Convert.ToString(lstDatas["OSSettlement"]);
                if (txtSettlement.Text == "Guarantor")
                {
                    pplGuarntor.Visible = true;
                    SetPickerEntry(pplGuarntor, Convert.ToString(lstDatas["Guarantor"]));
                }
            }
        }


        private void SetPickerEntry(PeopleEditor ppls, string SubmittedFor)
        {
            ArrayList _arrayList = new ArrayList();
            SPFieldUserValue fldUser = null;

            fldUser = new SPFieldUserValue(SPContext.Current.Web, SubmittedFor);

            PickerEntity _pickerEntity = new PickerEntity(); // PickerEntitiy use using Microsoft.SharePoint.WebControls
            _pickerEntity.Key = fldUser.LookupValue;
            _pickerEntity.IsResolved = true;
            _arrayList.Add(_pickerEntity);
            ppls.UpdateEntities(_arrayList);
            pkrReqUser = fldUser;
        }


        private void InvisibleButtons()
        {
            if (gvAccountablity.Rows.Count == 0)
                lblGVAcc.Visible = true;
            else
                lblGVAcc.Visible = false;

            btnCntrls.Visible = false;
            pnlView.Visible = true;

            pnlAccountablity.Visible = false;
            btnSubmit.Visible = false;
            btnApprove.Visible = false;
            btnReject.Visible = false;
            pnlForward.Visible = false;
            pnlCommentArea.Visible = false;
            upAtt.Visible = false;
            btnCancel.Value = "Close";

        }


        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //if (Page.IsValid)
            //{
            if (Request.QueryString["Mode"] == "Edit")
            {
                string formID = null;
                string refNo = Request.QueryString["RefID"];
                string taskItemID = Request.QueryString["TaskItemID"];
                string Approver = SPContext.Current.Web.CurrentUser.LoginName;

                if (!GetSetUserAccountablity())
                {
                    if (GetSendbackStatus())
                    {
                        if (CheckServersideValidation())
                        {
                            SPLongOperation lop = new SPLongOperation(this.Page);
                            lop.LeadingHTML = "<DIV><H4>Clearance Action form approval is in progress</H4></DIV>";
                            lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                            lop.Begin();

                            obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                            TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, null, false, 2, null, txtReqDivision.Text, lstUsers);
                            lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                        }
                    }
                    else
                    {

                        lblErrors.Visible = true; lblErrors.Text = "Can't be send back. User is not available";
                    }
                }
                else
                {
                    lblErrors.Visible = true; lblErrors.Text = "User already exist in accoutablity";
                }
            }
            else if (Request.QueryString["Mode"] == "New")
            {
                SaveFormDetails();
                //ClientScript.RegisterClientScriptBlock(GetType(), "Record Saved", "window.close", true);
            }
            //}
        }


        private void SetOSDetails()
        {

        }

        /// <summary>
        /// Add accountablity values to list or set accountablity values to gridview
        /// </summary>
        /// <returns></returns>
        private bool GetSetUserAccountablity()
        {
            bool ckUserInAccountablity = false;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {

                        SPList oList = oWeb.Lists.TryGetList(AccountablityLstName);
                        if (oList != null)
                        {
                            oWeb.AllowUnsafeUpdates = true;

                            if (ckSubmit.Value == "True")
                            {
                                if (LeaveRefID != null)
                                    camlQry = "<Where><And><Eq><FieldRef Name=\"LeaveReferenceNo\" /><Value Type=\"Text\">" + LeaveRefID + "</Value></Eq><Eq>" +
                                        "<FieldRef Name=\"Accountant\" /><Value Type=\"User\">" + CurrentUser + "</Value></Eq></And></Where>";
                                else
                                    camlQry = "<Where><And><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refID + "</Value></Eq><Eq>" +
                                        "<FieldRef Name=\"Accountant\" /><Value Type=\"User\">" + CurrentUser + "</Value></Eq></And></Where>";

                                oItems = obj.GetSPListItem(SiteURL, AccountablityLstName, camlQry);
                                if (oItems == null)
                                {
                                    oItems = oList.Items.Add();
                                    oItems["Title"] = refID;
                                    oItems["Reference_x0020_Number"] = refID;
                                    oItems["LeaveReferenceNo"] = LeaveRefID;

                                    SPUser User = oWeb.EnsureUser(CurrentUser);
                                    SPFieldUserValue UserName = new SPFieldUserValue(oWeb, User.ID, User.Name);
                                    oItems["Accountant"] = UserName;
                                    oItems["Division"] = txtReqDivision.Text;
                                    oItems["Accountablity"] = rdAccountablity.SelectedItem.Text;

                                    if (rdAccountablity.SelectedIndex == 0)
                                    {
                                        oItems["CashAdvance"] = txtCashAdv.Text;
                                        oItems["OtherReceivables"] = txtOtherRec.Text;
                                        oItems["ItemsPurchased"] = txtItemPur.Text;
                                    }
                                    oItems.Update();
                                    ckUserInAccountablity = false;
                                }
                                else
                                {
                                    ckUserInAccountablity = true;
                                }
                            }
                            else
                            {
                                camlQry = "<Where><Or><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refID + "</Value></Eq><Eq>" +
                                    "<FieldRef Name=\"LeaveReferenceNo\" /><Value Type=\"Text\">" + LeaveRefID + "</Value></Eq></Or></Where><OrderBy>" +
                                    "<FieldRef Name=\"Created\" Ascending=\"False\" /></OrderBy>";
                                oItemsColl = obj.GetSPListItems(SiteURL, AccountablityLstName, camlQry);
                                if (oItemsColl != null)
                                {
                                    gvAccountablity.DataSource = oItemsColl.GetDataTable();
                                    gvAccountablity.DataBind();
                                }

                            }
                            oWeb.AllowUnsafeUpdates = false;
                        }
                    }
                }
            });

            return ckUserInAccountablity;
        }


        /// <summary>
        /// Save Form details 
        /// Add Items in Main List
        /// Add Items in Task List
        /// Add Items in Comments List
        /// Add Attachment to Attachment Library
        /// </summary>

        private void SaveFormDetails()
        {
            SPLongOperation lop = new SPLongOperation(this.Page);
            lop.LeadingHTML = "<DIV><H4>Clearance Action form submission is in progress...</H4></DIV>";
            lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
            lop.Begin();

            string taskItemID = Request.QueryString["TaskItemID"];
            string Approver = SPContext.Current.Web.CurrentUser.LoginName;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    obj.AutoNoGeneration(MainLstName, DocumentTypesList, lblClrReqNo, SiteURL);
                    ClearanceRequestNo = Convert.ToString(lblClrReqNo.Text).Trim();
                    if (ClearanceRequestNo.Contains(DateTime.Now.Year.ToString()))
                    {
                        lstGuid = obj.AddClearance_Items(SiteURL, MainLstName, TaskLstName, CmntsLstName, AttLibName, upfile, WorkflowConfigList, pplcnt,
                            lblClrReqNo.Text, dtReqDate.SelectedDate.Date, txtLeaveRefNo.Text, dtLeaveReqDate.SelectedDate.Date, pplReqUser.CommaSeparatedAccounts,
                            txtReqEmpId.Text, txtReqDivision.Text,
                            txtReqDesignation.Text, ClearanceType, dtEffectiveon.SelectedDate.Date, CurrentUser, rdClearanceType.SelectedIndex,
                            TxtComments.Text, txtReqDepartment.Text, dtLeaveStartDT.SelectedDate.Date, dtLeaveEndDT.SelectedDate.Date);

                    }
                    else
                    {
                        lblError.Text = "Master list details not in Doecument Types"; lblError.ForeColor = System.Drawing.Color.Red;
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "SaveFormDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
            lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");

        }

        /// <summary>
        /// check the user availability
        /// </summary>
        /// <returns></returns>


        protected void btnApprove_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string formID = null;
                string refNo = Request.QueryString["RefID"];
                string taskItemID = Request.QueryString["TaskItemID"];
                string Approver = SPContext.Current.Web.CurrentUser.LoginName;
                if (GetSendbackStatus())
                {
                    if (CheckServersideValidation())
                    {
                        SPLongOperation lop = new SPLongOperation(this.Page);
                        lop.LeadingHTML = "<DIV><H4>HR Request form approval is in progress</H4></DIV>";
                        lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                        lop.Begin();

                        if (GetEmpDept() != "Human Resource") // Check the User department and assign next approval task to SubmittedFor user, the parameter intimate as "true";
                        {
                            if (obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                               TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, false))
                                ClearanceStatusInLeaveForm(); // It will affect while the form gets approved status
                        }
                        else
                        {
                            if (obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                               TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, true))
                                ClearanceStatusInLeaveForm(); // It will affect while the form gets approved status
                        }

                        if (plnSettle.Visible == true)
                            UpdateOS_Status();

                        lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                    }
                }
                else
                {
                    //lblError.Text = "Can't be send back. User is not available";
                    SPLongOperation lop = new SPLongOperation(this.Page);
                    lop.LeadingHTML = "<DIV><H4>HR Request form approval is in progress</H4></DIV>";
                    lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                    lop.Begin();

                    if (obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                    TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, true))
                        ClearanceStatusInLeaveForm();
                    lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                }
            }
        }


        void btnReject_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SPLongOperation lop = new SPLongOperation(this.Page);
                lop.LeadingHTML = "<DIV><H4>Leave Request form rejection in progress</H4></DIV>";
                lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                lop.Begin();


                //string formID = null;// Request.QueryString["FormID"];
                string refNo = Request.QueryString["RefID"];
                string TaskItemID = Request.QueryString["TaskItemID"];

                try
                {

                    SPFieldUserValue userValue = obj.GetSubmittedUser(SiteURL, lstGuid, refNo);
                    trigWFClass.RejectTask(SiteURL, Request.QueryString["TaskItemID"], TaskLstName, MainLstName, Request.QueryString["RefID"]);

                    if (!string.IsNullOrEmpty(upfile.FileName))
                        demandVoucherclass.AddAttachement(SiteURL, AttLibName, refNo, lstGuid, upfile);
                    // Reject user and comments updation
                    string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;
                    obj.SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, CurrentUser, TxtComments.Text, 0);


                }
                catch (Exception ex)
                {
                    ErrorMsgs = "Trig_AMJ_HR_Forms :: Leave Request Form" + " :: " + "Parent" + " :: " + "Reject";
                    obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }

                lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");

            }
        }


        /// <summary>
        /// Set settlement process is done by user or Guarantor
        /// </summary>
        private void UpdateOS_Status()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            oWeb.AllowUnsafeUpdates = true;
                            oItems = oWeb.Lists.TryGetList(MainLstName).GetItemById(ClearanceItemID);
                            if (oItems != null)
                            {
                                oItems["OSSettlement"] = Convert.ToString(rdOS.SelectedItem.Text);
                                if (rdOS.SelectedIndex == 1)
                                {

                                    SPUser User = oWeb.EnsureUser(pplGuarantors.CommaSeparatedAccounts);//oWeb.SiteUsers[pplGuarantors.CommaSeparatedAccounts];
                                    SPFieldUserValue guarantor = new SPFieldUserValue(oWeb, User.ID, User.Name);
                                    oItems["Guarantor"] = guarantor;
                                }
                                oItems.Update();
                            }
                            oWeb.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
            catch (Exception)
            {

                throw;
            }

        }

        /// <summary>
        /// Set clearance status to Leave Request Form List
        /// </summary>
        private void ClearanceStatusInLeaveForm()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPQuery qry = new SPQuery();
                            camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + LeaveRefID + "</Value></Eq></Where>";
                            qry.Query = camlQry;

                            SPList oList = oWeb.Lists.TryGetList(SourceLstName);
                            if (oList != null)
                            {
                                oWeb.AllowUnsafeUpdates = true;
                                oItems = oList.GetItems(qry)[0];
                                if (oItems != null)
                                    oItems["ClearanceStatus"] = "Yes";
                                oItems.Update();
                                oWeb.AllowUnsafeUpdates = false;
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "ResumptionStatusInLeaveForm";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }


        public bool GetSendbackStatus()
        {
            bool status = true;
            if (rtbSendBack.Checked)
            {
                SPFieldUserValue ofldUser = demandVoucherclass.getSendBackUserfNametoAssignLabelText(SiteURL, TaskLstName, Convert.ToInt16(Request.Params["TaskItemID"]), lblClrReqNo.Text, rtbSendBack, rtbForward, lblError);
                if (ofldUser == null)
                {
                    status = false;
                }
            }
            return status;
        }

        /// <summary>
        /// Check people editor validations
        /// </summary>
        /// <returns></returns>

        public bool CheckServersideValidation()
        {
            bool rval = true;
            if (rtbForwardOthers.Checked)
            {
                if (pplcnt.Accounts.Count > 0)
                {
                    rval = true;
                }
                else
                {
                    rval = false;
                    lblError.Text = "Please enter the user name to forward";
                }
            }
            return rval;
        }

        /// <summary>
        /// Radio button visibility for dynamic users
        /// </summary>
        /// <param name="tasktype"></param>
        /// <param name="optional"></param>
        /// <param name="OptionalUserName"></param>

        public void RadioButtionListvisibility(SPWeb oweb, string tasktype, bool optional, string OptionalUserName, int WFOrder)
        {
            try
            {
                if (Request.QueryString["Mode"] == "New")
                {
                    pnlForward.Visible = false;
                }
                else if (Request.QueryString["Mode"] == "Edit")
                {
                    if (tasktype == "Static")
                    {
                        pnlForward.Visible = false;
                    }
                    else if (tasktype == "Dynamic")
                    {
                        setRadioButtonVisibilityforDynamicType(WFOrder);
                    }
                    else if (tasktype == "UP Attribute")
                    {
                        pnlForward.Visible = false;
                    }
                    else if (tasktype == "EC (Externally Configured)")
                    {
                        pnlForward.Visible = false;
                    }

                    buttonVisibilty = demandVoucherclass.getForwardbuttonVisibility(SiteURL, WorkflowConfigList, MainLstName, WFOrder);
                    if (buttonVisibilty[3] == "True")
                    {
                        btnApprove.Visible = true;
                        btnReject.Visible = true;
                        btnSubmit.Visible = false;
                    }
                    else
                    {
                        btnApprove.Visible = false;
                        btnReject.Visible = false;
                        btnSubmit.Visible = true;
                    }
                    if (buttonVisibilty[4] == "False")
                    {
                        pnlCommentArea.Visible = false;
                    }

                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "RadioButtionListvisibility";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        /// <summary>
        /// set radion buttons visibilty for the dynamic work flow users
        /// </summary>
        /// <param name="WFOrder"></param>

        public void setRadioButtonVisibilityforDynamicType(int WFOrder)
        {
            try
            {
                buttonVisibilty = demandVoucherclass.getForwardbuttonVisibility(SiteURL, WorkflowConfigList, MainLstName, WFOrder);
                if (buttonVisibilty[0] == "True")
                {
                    rtbSendBack.Visible = true;
                    rtbSendBack.Checked = true;
                }
                else
                {
                    rtbSendBack.Visible = false;
                }
                if (buttonVisibilty[1] == "True")
                {
                    rtbForwardOthers.Visible = true;
                }
                else
                {
                    rtbForwardOthers.Visible = false;
                }

                if (buttonVisibilty[2] == "True")
                {
                    rtbForward.Visible = true;
                }
                else
                {
                    rtbForward.Visible = false;
                }
                if (buttonVisibilty[0] == "False" && buttonVisibilty[1] == "False" && buttonVisibilty[2] == "False")
                {
                    pnlForward.Visible = false;
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "setRadioButtonVisibilityforDynamicType";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        protected void gvAccountablity_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                decimal rowTotal = Convert.ToDecimal
                            (DataBinder.Eval(e.Row.DataItem, "CashAdvance"));
                grdTotal = grdTotal + rowTotal;

            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                Label lbl = (Label)e.Row.FindControl("lblTotal");
                lbl.Text = grdTotal.ToString("c");
            }
        }



        /// <summary>
        /// Get List users from group
        /// </summary>
        private void AssignedNotMe()
        {

            if (pplGuarantors.Entities.Count > 0)
            {
                PickerEntity pkrGterer = (PickerEntity)pplGuarantors.Entities[0];

                string loggedUser = SPContext.Current.Web.CurrentUser.Name;

                if (pkrReqUser != null)
                {
                    if (pkrReqUser.LookupValue == loggedUser || pkrGterer.DisplayText == loggedUser)
                    {
                        pplGuarantors.Entities.Clear();
                        pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Same user entry not allowed!');</script>"));
                    }
                }

            }
        }

    }
}
